package middle;

public class Solution_390 {

    public static void main(String[] args) {
        Solution_390 model = new Solution_390();
        System.out.println(model.lastRemaining(9));
        System.out.println(model.lastRemaining(1));
    }

    public int lastRemaining(int n) {
        int count = n, a1 = 1, step = 1;
        boolean direct = true;
        while (count > 1) {
            if (direct || count % 2 == 1) {
                a1 = a1 + step;
            }
            step <<= 1;
            count >>= 1;
            direct = !direct;
        }
        return a1;
    }
}
